import {
  createSlice,
  PayloadAction,
  createAsyncThunk,
  ActionReducerMapBuilder
} from "@reduxjs/toolkit"
import axios from "axios"

interface ProductDetailState {
  loading: boolean
  error: string | null
  data: any
}

const initialState: ProductDetailState = {
  loading: true,
  error: null,
  data: null
}

export const getProductDetail = createAsyncThunk(
  "productDetail/getProductDetail",
  async (touristRouteId: string, thunkAPI) => {
    const { data } = await axios.get(
      `http://123.56.149.216:8080/api/touristRoutes/${touristRouteId}`
    )
    return data
  }
)

export const productDetailSlice = createSlice({
  name: "productDetail",
  initialState,
  reducers: {},
  // 与reducers不同，extraReducers每个单独的case reduce你会生成新的动作类型或动作创建者
  extraReducers: (builder: ActionReducerMapBuilder<ProductDetailState>) => {
    builder
      .addCase(getProductDetail.pending, (state) => {
        // 处理pending状态，比如设置加载标志
        // return { ...state, loading: true };
        state.loading = true
      })
      .addCase(getProductDetail.fulfilled, (state, action) => {
        // 处理fulfilled状态，使用action.payload更新state
        state.data = action.payload
        state.loading = false
        state.error = null
      })
      .addCase(getProductDetail.rejected, (state, action) => {
        // 处理rejected状态，比如设置错误信息
        //   const ddd = action.payload;
        state.loading = false
        // state.error = action.payload
      })
  }
  // extraReducers: {
  //   [getProductDetail.pending.type]: (state) => {
  //     // return { ...state, loading: true };
  //     state.loading = true
  //   },
  //   [getProductDetail.fulfilled.type]: (state, action) => {
  //     state.data = action.payload
  //     state.loading = false
  //     state.error = null
  //   },
  //   [getProductDetail.rejected.type]: (
  //     state,
  //     action: PayloadAction<string | null>
  //   ) => {
  //     state.loading = false
  //     state.error = action.payload
  //   }
  // }
})
